package com.dingreading.cloud.common.util.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 合并策略
 */
public class CustomMergeStrategy implements SheetWriteHandler {

    private List<?> dataList;
    private List<MergeFieldBean> mergeFieldList;

    public CustomMergeStrategy(List<?> dataList, List<MergeFieldBean> mergeFieldList) {
        this.dataList = dataList;
        this.mergeFieldList = mergeFieldList;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        SheetWriteHandler.super.afterSheetCreate(writeWorkbookHolder, writeSheetHolder);

        // 获取当前sheet
        Sheet sheet = writeSheetHolder.getSheet();

        // 获取数据列表的大小
        int dataSize = dataList.size();
        if (dataSize <= 1) {
            return; // 数据量小于等于1不需要合并
        }

        // 合并策略：按字段将相同数据合并
        for (int i = 0; i < mergeFieldList.size(); i++) {
            MergeFieldBean bean = mergeFieldList.get(i);
            mergeSameCells(sheet, dataList, bean.getFieldName(), bean.getIndex());
        }
    }

    /**
     * 合并相同内容的单元格
     *
     * @param sheet       工作表
     * @param dataList    数据列表
     * @param fieldName   字段名
     * @param columnIndex 列索引
     */
    private void mergeSameCells(Sheet sheet, List<?> dataList, String fieldName, int columnIndex) {
        int startRow = 1; // 从第2行开始（第1行是标题）
        int endRow = 1;
        Object previousValue = null;

        try {
            for (int i = 0; i < dataList.size(); i++) {
                Object currentValue = getFieldValue(dataList.get(i), fieldName);

                if (previousValue != null && !previousValue.equals(currentValue)) {
                    // 值发生变化，合并之前的单元格
                    if (endRow - startRow > 0) {
                        CellRangeAddress region = new CellRangeAddress(startRow, endRow, columnIndex, columnIndex);
                        sheet.addMergedRegion(region);
                    }
                    startRow = i + 1; // +1 是因为数据行从第2行开始
                }

                endRow = i + 1; // +1 是因为数据行从第2行开始
                previousValue = currentValue;
            }

            // 处理最后一组相同数据
            if (endRow - startRow > 0) {
                CellRangeAddress region = new CellRangeAddress(startRow, endRow, columnIndex, columnIndex);
                sheet.addMergedRegion(region);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过反射获取字段值
     */
    private Object getFieldValue(Object obj, String fieldName) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return field.get(obj);
    }
}
